//
//  UISearchBar+QTAdd.m
//  QTCategory
//
//  Created by 张俊博 on 2017/9/28.
//  Copyright © 2017年 CISDI. All rights reserved.
//

#import "UISearchBar+QTAdd.h"
#import <objc/runtime.h>
#import "UIView+QTAdd.h"
#import "QTCategoryMacro.h"
#import "NSObject+QTAddForKVO.h"
#import "NSString+QTAdd.h"

@interface UISearchBar (QTAdd_)

@property (nonatomic, strong) UIImage *p_image;
@property (nonatomic, strong) NSAttributedString *p_attributedPlaceholder;
@property (nonatomic, strong) CALayer *p_layerPlaceHolder;

@end

@implementation UISearchBar (QTAdd_)

- (UIImage *)p_image {
    return objc_getAssociatedObject(self, @selector(p_image));
}

- (void)setP_image:(UIImage *)p_image {
    objc_setAssociatedObject(self, @selector(p_image), p_image, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSAttributedString *)p_attributedPlaceholder {
    return objc_getAssociatedObject(self, @selector(p_attributedPlaceholder));
}

- (void)setP_attributedPlaceholder:(NSAttributedString *)p_attributedPlaceholder {
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithAttributedString:p_attributedPlaceholder];
    [attr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, attr.length)];
    objc_setAssociatedObject(self, @selector(p_attributedPlaceholder), attr, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (CALayer *)p_layerPlaceHolder {
    return objc_getAssociatedObject(self, @selector(p_layerPlaceHolder));
}

- (void)setP_layerPlaceHolder:(CALayer *)p_layerPlaceHolder {
    objc_setAssociatedObject(self, @selector(p_layerPlaceHolder), p_layerPlaceHolder, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UITextField *)p_textFiled {
    return (UITextField *)[self subViewOrSelfWithClass:[UITextField class]];
}

@end

@implementation UISearchBar (QTAdd)

- (void)dealloc {
    if (objc_getAssociatedObject(self, @selector(adjustsPlaceHolderCenterForIOS11))) {
        [self p_removeNotificationObserver];
        [self removeObserverBlocks];
    }
}

- (void)adjustsPlaceHolderCenterForIOS11 {
    if (@available(iOS 11.0, *)) {
        if (!objc_getAssociatedObject(self, @selector(adjustsPlaceHolderCenterForIOS11))) {
            objc_setAssociatedObject(self, @selector(adjustsPlaceHolderCenterForIOS11), @"Launched", OBJC_ASSOCIATION_RETAIN);
            [self p_addNotificationObserver];
        }
        [self p_resetTextFiled:self.isFirstResponder];
    }
}

- (void)p_addNotificationObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidBeginEditingNotification:) name:UITextFieldTextDidBeginEditingNotification object:[self p_textFiled]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidEndEditingNotification:) name:UITextFieldTextDidEndEditingNotification object:[self p_textFiled]];
}

- (void)p_removeNotificationObserver {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)textFieldDidBeginEditingNotification:(NSNotification *)notification
{
    [self p_resetTextFiled:YES];
}

- (void)textFieldDidEndEditingNotification:(NSNotification *)notification
{
    [self p_resetTextFiled:NO];
}

- (void)p_resetTextFiled:(BOOL)isActive {
    
    if (@available(iOS 11.0, *)) {
        UITextField *textField = [self p_textFiled];
        
        if (!objc_getAssociatedObject(self, _cmd)) {
            objc_setAssociatedObject(self, _cmd, @"Launched", OBJC_ASSOCIATION_RETAIN);
            self.p_image = [(UIImageView *)textField.leftView image];
            self.p_attributedPlaceholder = textField.attributedPlaceholder;
            @weakify(self)
            [textField addObserverBlockForKeyPath:@"attributedPlaceholder" block:^(UITextField *textField, id  _Nullable oldVal, id  _Nullable newVal) {
                @strongify(self)
                if (!newVal) {
                    return ;
                }
                self.p_attributedPlaceholder = textField.attributedPlaceholder;
                [self refreshPlaceHolderLayer:textField.isFirstResponder];
            }];
            [textField addObserverBlockForKeyPath:@"placeholder" block:^(UITextField *textField, id  _Nullable oldVal, id  _Nullable newVal) {
                @strongify(self)
                if (!self.p_attributedPlaceholder || !newVal) {
                    return ;
                }
                NSDictionary *attrDic = [self.p_attributedPlaceholder attributesAtIndex:0 effectiveRange:NULL];
                self.p_attributedPlaceholder = [[NSAttributedString alloc] initWithString:newVal attributes:attrDic];
                [self refreshPlaceHolderLayer:textField.isFirstResponder];
                
                [textField setValue:nil forKey:@"placeholder"];
            }];
        }
        
        [self refreshPlaceHolderLayer:isActive];
        
        if (isActive) {
            textField.attributedPlaceholder = self.p_attributedPlaceholder;
        } else {
            textField.attributedPlaceholder = nil;
        }
    }
}

- (void)refreshPlaceHolderLayer:(BOOL)isActive {
    
    if (self.text && self.text.length>0) {
        isActive = YES;
    }
    
    UITextField *textField = [self p_textFiled];
    if (isActive) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.p_image.size.width, self.p_image.size.height)];
        imageView.image = self.p_image;
        textField.leftView = imageView;
    } else {
        textField.leftView = nil;
    }
    
    if (self.p_layerPlaceHolder) {
        [self.p_layerPlaceHolder removeFromSuperlayer];
    }
    
    self.p_layerPlaceHolder = [CALayer layer];
    self.p_layerPlaceHolder.frame = CGRectMake(0, 0, SCREEN_WIDTH-16, 29);
    
    CALayer *imageLayer = [CALayer layer];
    imageLayer.contents = (id)self.p_image.CGImage;
    
    CATextLayer *textLayer = [CATextLayer layer];
    textLayer.contentsScale = [UIScreen mainScreen].scale;
    textLayer.alignmentMode = kCAAlignmentLeft;
    textLayer.string = self.p_attributedPlaceholder;
    
    CGFloat padding = 10;
    
    CGSize imageSize = self.p_image.size;
    UIFont *font = [self.p_attributedPlaceholder attribute:NSFontAttributeName atIndex:0 effectiveRange:NULL];
    CGSize textSize = [self.p_attributedPlaceholder.string sizeForFont:font size:CGSizeMake(MAXFLOAT, MAXFLOAT) mode:NSLineBreakByWordWrapping];
    imageLayer.frame = CGRectMake((self.p_layerPlaceHolder.bounds.size.width-imageSize.width-padding-textSize.width)/2,
                                  (self.p_layerPlaceHolder.bounds.size.height-imageSize.height)/2,
                                  imageSize.width,
                                  imageSize.height);
    textLayer.frame = CGRectMake(CGRectGetMaxX(imageLayer.frame) + padding,
                                 (self.p_layerPlaceHolder.bounds.size.height-textSize.height)/2,
                                 textSize.width,
                                 textSize.height);
    [self.p_layerPlaceHolder addSublayer:imageLayer];
    [self.p_layerPlaceHolder addSublayer:textLayer];
    
    UIView *borderView = [self subViewOrSelfWithClass:NSClassFromString(@"_UITextFieldContentView")];
    
    self.p_layerPlaceHolder.hidden = isActive;
    [borderView.layer addSublayer:self.p_layerPlaceHolder];
}



@end
